package com.uchedao.seller.ui.car.publish.condition;

import android.content.ContentValues;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.module.Condition;
import com.uchedao.seller.module.Detection;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.module.ResultInt;
import com.uchedao.seller.ui.car.adapter.EngineManualAdapter;
import com.uchedao.seller.ui.car.adapter.EngineManualAdapter.EngineManualAdapterListener;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersListView;

import java.util.ArrayList;

/**
 * 发动机&变速箱
 */
public class ConditionEngineView extends UCheDaoRelativeLayout implements EngineManualAdapterListener {


    private Condition condition;

    public ConditionEngineView(Context context) {
        super(context);
    }

    public ConditionEngineView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionEngineView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private EngineManualAdapter engineManualAdapter;

    @Override
    public boolean save() {

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));
            return noEmptyTerm();
        }

        return false;
    }

    /**
     * 没有空项
     */
    public boolean noEmptyTerm() {
        for(int i=0; i<engineManualAdapter.array.size(); i++) {
            if(engineManualAdapter.array.get(i).getValues()!=null && engineManualAdapter.array.get(i).getValues().size() <= 0)
                return false;
        }
        return true;
    }

    /**
     * 一键全部正常
     */
    public void checkAllOk() {
        for(int i=0; i<engineManualAdapter.array.size(); i++) {
            if(engineManualAdapter.array.get(i).getValues()!=null && engineManualAdapter.array.get(i).getValues().size()<=0)
                engineManualAdapter.array.get(i).getValues().add(0);
        }
        engineManualAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean dataChanged() {
//        L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {
//        LayoutInflater.from(mContext).inflate(R.layout.condition_obd_foot, this);

        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);
        // odb_listview
        StickyListHeadersListView stickyListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);

        //暂时先不加  ↓
//        stickyListHeadersListView.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.view_condition_engine_obd, null));
////        stickyListHeadersListView
////                .addFooterView(inflate(R.layout.condition_obd_manual));
//        stickyListHeadersListView.addFooterView(LayoutInflater.from(mContext).inflate(R.layout.condition_obd_foot, null));
//        stickyListHeadersListView.setAdapter(new EngineObdAdapter(mContext, getEngineOdbData()));
//
//        TextView subjectTv = (TextView) findViewById(R.id.subject_tv);
//        subjectTv.setText(R.string.obd_check_parts);
//
////         连接状态
//        TextView obdConection = (TextView) findViewById(R.id.text_obd_connection);
//        obdConection.setTextColor(Color.RED);
//        obdConection.setText(R.string.unconnection);
//        obdConection.setEnabled(false);
//
//        // 开启连接按钮
//        final TextView connectObdLayout = (TextView) findViewById(R.id.connect_tv);
//        connectObdLayout.setEnabled(false);
//
//        // 是否支持OBD设备
//        CheckBox obdUnfundCb = (CheckBox) findViewById(R.id.obd_unfund_cb);
//        obdUnfundCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                connectObdLayout.setEnabled(!isChecked);
//            }
//        });

        //暂时先不加  ↑

//        ListView odbFootList = (ListView) findViewById(R.id.obd_list);
        engineManualAdapter = new EngineManualAdapter(mContext, getEngineManualData(), this);
        engineManualAdapter.setMinWidth(100);
//        engineManualAdapter.setDefaultValue();
        stickyListHeadersListView.setAdapter(engineManualAdapter);
//        fixListViewHeight(stickyListHeadersListView);
    }

    public void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }
        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
            View listViewItem = listAdapter.getView(index, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initListener() {

    }

    /**
     * 发动机&变速箱数据
     *
     * @return
     */
    private ResultInt[] getEngineOdbData() {

        String[] values = GlobalInfo.resources.getStringArray(R.array.engine_obd_values);
        ResultInt[] results = new ResultInt[values.length];
        for (int i = 0; i < results.length; i++) {
            results[i] = new ResultInt();
            results[i].name = values[i];
            results[i].result = -1;
        }

        return results;
    }

    /**
     * 发动机&变速箱数据
     *
     * @return
     */
    private ArrayList<Detection> getEngineManualData() {
        ArrayList<Detection> list = new ArrayList<Detection>();

        String[] texts = GlobalInfo.resources.getStringArray(R.array.performance_entries);
        int i = 0;
        String header = GlobalInfo.resources.getString(R.string.condition_other);

        // 发动机工况
        if (condition.performance.engine_check_value == null)
            condition.performance.engine_check_value = new ArrayList<Integer>();
        Detection item = new Detection(Detection.TYPE_MULTIPLE);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_engine_check_select_values);
        item.setValues(condition.performance.engine_check_value);
        item.setText(texts[i++]);
        list.add(item);

        // 排气颜色
        item = new Detection(Detection.TYPE_SINGLE_CHOICE);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_gas_color_select_values);
        item.setValue(condition.performance.gas_color_value);
        item.setText(texts[i++]);
        list.add(item);

        // 换档机构
        if (condition.performance.gears_value == null)
            condition.performance.gears_value = new ArrayList<Integer>();
        item = new Detection(Detection.TYPE_MULTIPLE);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_gears_select_values);
        item.setValues(condition.performance.gears_value);
        item.setText(texts[i++]);
        list.add(item);

        // 转向性能
        if (condition.performance.steering_value == null)
            condition.performance.steering_value = new ArrayList<Integer>();
        item = new Detection(Detection.TYPE_MULTIPLE);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_steering_select_values);
        item.setValues(condition.performance.steering_value);
        item.setText(texts[i++]);
        list.add(item);

        // 漏油部位
        if (condition.performance.oil_spill_value == null)
            condition.performance.oil_spill_value = new ArrayList<Integer>();
        item = new Detection(Detection.TYPE_MULTIPLE);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_oil_spill_select_values);
        item.setValues(condition.performance.oil_spill_value);
        item.setText(texts[i++]);
        list.add(item);

        // 噪音检查
//        item = new Detection(Detection.TYPE_TWO_SELECT);
//        item.setHeader(header);
//        item.setRequestFocus(true);
//        item.setResId(R.array.funciton_two_select_values);
//        item.setKey(mContext.getString(R.string.decibel_dB));// 设置单位
//        item.setText(texts[i++]);
//        item.setStrValue(condition.performance.noise_value);
//        list.add(item);

        // 发动机是滞有拆卸痕迹
        item = new Detection(Detection.TYPE_TWO_SELECT);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_engine_removal);
        item.setValue(condition.performance.engine_teardown_value);
        item.setText(texts[i++]);
        list.add(item);

        // 发动机内缸有无损伤
        item = new Detection(Detection.TYPE_TWO_SELECT);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_engine_damage);
        item.setValue(condition.performance.engine_inner_casing_value);
        item.setText(texts[i++]);
        list.add(item);

        // 变速箱挂档是否顺畅
        item = new Detection(Detection.TYPE_TWO_SELECT);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_transmission_smooth);
        item.setValue(condition.performance.gearbox_change_value);
        item.setText(texts[i++]);
        list.add(item);

        // 变速有无异响
        item = new Detection(Detection.TYPE_TWO_SELECT);
        item.setHeader(header);
        item.setRequestFocus(true);
        item.setResId(R.array.performance_speed);
        item.setValue(condition.performance.gearbox_noise_value);
        item.setText(texts[i++]);
        list.add(item);

        return list;
    }


    /**
     * 得到值
     *
     * @param position
     * @return
     */
    private String getTextValue(int position) {
        Detection detection = (Detection) engineManualAdapter.getItem(position);
        // 二选一 三选一
        if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0
                || (detection.getValueType() & Detection.TYPE_SINGLE_CHOICE) != 0
                || (detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());
            return values[detection.getValue()];

            // 多选
        } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            ArrayList<Integer> ints = detection.getValues();

            // 若为空值，默认为0
            if (ints.size() == 0)
                ints.add(0);

            String value = "";
            for (int i : ints) {
                if (TextUtils.isEmpty(value))
                    value = values[i];
                else
                    value += "," + values[i];
            }
            return value;
        }
        return null;
    }

    @Override
    public void onResult(int position, String value) {
        switch (position) {
            case 5:// 噪音检查( 大等于85为故障 )
                condition.performance.noise_value = value;
                condition.performance.noise = value;
                // try {
                // if (TextUtils.isEmpty(value))
                // condition.performance.noise = 0;
                // else
                // condition.performance.noise = Integer.parseInt(value);
                // } catch (NumberFormatException e) {
                // condition.performance.noise = 0;
                // }
                break;
        }

    }

    @Override
    public void onResult(int position, int value) {

        L.w("onResult(" + position + "," + value + ")");
        switch (position) {

            case 1:// 排气颜色
                condition.performance.gas_color_value = value;
                condition.performance.gas_color = getTextValue(position);
                L.w("排气颜色 = " + condition.performance.gas_color);
                break;

            case 6:// 发动机是否有拆卸痕迹
                condition.performance.engine_teardown_value = value;
                condition.performance.engine_teardown = getTextValue(position);
                break;

            case 7:// 发动机内缸有无损伤
                condition.performance.engine_inner_casing_value = value;
                condition.performance.engine_inner_casing = getTextValue(position);
                break;

            case 8:// 变速箱挂档是否顺畅
                condition.performance.gearbox_change_value = value;
                condition.performance.gearbox_change = getTextValue(position);
                break;

            case 9:// 变速有无异响
                condition.performance.gearbox_noise_value = value;
                condition.performance.gearbox_noise = getTextValue(position);
                break;
        }

    }

    @Override
    public void onResult(int position, ArrayList<Integer> value) {
        switch (position) {
            case 0:// 工况检测
                condition.performance.engine_check_value = value;
                condition.performance.engine_check = getTextValue(position);
                break;

            case 2:// 换档机构
                condition.performance.gears_value = value;
                condition.performance.gears = getTextValue(position);
                break;

            case 3:// 转向性能
                condition.performance.steering_value = value;
                condition.performance.steering = getTextValue(position);
                break;

            case 4:// 漏洞部位
                condition.performance.oil_spill_value = value;
                condition.performance.oil_spill = getTextValue(position);
                break;

        }

    }

}
